<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    width="45%"
    :show-close="false"
    :visible.sync="visible">
    <el-form  :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="160px">
      <el-form-item style="width:100%" class="oneCls" label="英文名称：" prop="interfaceName">
        <el-input style="width:84%" @input="changeUserInput(dataForm.interfaceName)" v-model="dataForm.interfaceName" placeholder="请输入英文名称"></el-input>
        <p class="info">
          <span>说明：输入的内容是纯英文，包含大小写</span>
          <span style="color:red;">{{ textInfo }}</span>
        </p>
        <el-button :disabled="isYzFlag" :type="isYzFlag?'success':'primary'" @click="yzParmData(dataForm.interfaceName)">
          <span v-if="isYzFlag"><i class="el-icon-success"></i> 通过</span>
          <span v-else><i class="el-icon-menu"></i>验证</span>
        </el-button>
      </el-form-item>
      <el-form-item  v-if="isYzFlag" label="接口中文名：" prop="name">
        <el-input v-model="dataForm.name" placeholder="请输入接口中文名"></el-input>
        <p class="info"></p>
      </el-form-item>
      
      <el-form-item  v-if="isYzFlag" label="body参数：" prop="jsonBody">
        <el-input :rows="4" @focus="editJson('jsonBody',dataForm.jsonBody)"  type="textarea" v-model="dataForm.jsonBody" placeholder=""></el-input>
        <p class="info" style="top:215px;">说明：接口请求的body参数</p>
      </el-form-item>
    </el-form>
    <div style="padding-left:60px;color:#17B3A3;word-wrap: break-word;word-break: normal;" v-if="veriicationStr!=''"><span>验证成功：</span>{{veriicationStr}}</div>
    <span  slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>



    <el-dialog
      width="30%"
      title="JSON参数编辑"
      :visible.sync="editPostJsonFlag"
      append-to-body>
      <div v-if="editPostJsonFlag">
        <vue-json-editor
          v-model="resultInfo"
          :showBtns="false"
          :mode="'code'"
          @json-change="onJsonChange"
          @json-save="onJsonSave"
          @has-error="onError"
        />
        <br>
      <el-button type="primary" @click="checkJson">确定</el-button>
    </div>
    </el-dialog>
  </el-dialog>
</template>

<script>
  import Vue from 'vue'
  import request from '@/utils/request'
  import vueJsonEditor from 'vue-json-editor'
  export default {
    components:{
      vueJsonEditor
    },
    data () {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('英文名称不能为空'));
        } else {
          callback();
        }
      };
      return {
        pageIdList:[],
        textInfo:"",
        isYzFlag:false,
        conmitFormData:null,
        jsonType:'',
        veriicationStr:"",
        hasJsonFlag:true,  // json是否验证通过
        // json数据
        resultInfo: {},

        methodsList: [],
        options: [],
        editPostJsonFlag: false,
        // -------------
        visible: false,
        menuList: [],
        menuListTreeProps: {
          label: 'name',
          children: 'children'
        },
        dataForm: {
          interfaceName: '',
          name:"",
          jsonBody:""
        },
        dataRule: {}
      }
    },
    methods: {
      changeRadio(){
       if(this.dataForm.needToken=='1'){

       }
      },
      changeUserInput(v){
        this.isYzFlag = false
        if(v.length==0){
          this.textInfo = '请先输入英文名称'
          return
        }else{
          this.textInfo = ''
        }
        //清空所有字段数据
      },
      resetData(){
        this.methodsList.forEach((item,index)=> {
          item.type = ""
        })
        this.dataForm= {
          interfaceName: this.dataForm.interfaceName,
          name:"",
          url:"",
          heard:"",
          needToken:"",
          tokenId:"",
          tokenPath:"",
          tokenData:"",
          tokenPrefix:"",
          method:"",
          dataPath:"",
          body: '',
          param:"",
          firstOne:"",
          keyReplace:"",
          keyReplaceValue:"",
          redisNeed:"",
          dataType:"",
          remark:"",
          jsonBody:"",
          jsonHeard:"",
          jsonKeyReplaceValue:""
        }
      },
      yzParmData(v){
        if(!v||v.length==0){
          this.textInfo = '请先输入英文名称'
          return
        }
        if(this.isYzFlag){
          return
        }
        request({
          url: '/ht-datadevelop/table/jsondata/getInterfaceNameCompliance',
          method: 'post',
          data:{interfaceName:v}
        }).then((res) => {
          if(res.data.success){
            this.isYzFlag = true
            this.textInfo = ""
            this.resetData()
          }else{
            this.textInfo = "【"+res.data.message+"】"
          }
        })
      },
      closeDialog(){
        this.veriicationStr=''
        this.dataForm = {
          interfaceName: '',
          url: '',
          method: '0',
          contentType: '',
          keyPath: '',
          body: '',
          parameter: '',
          status:'',
          inlay:'',
          heardData:'',
          inlayParameter:'',
          bodyData:''
        }
        this.resultInfo = {}
        this.visible = false
        this.$refs['dataForm'].resetFields()
      },
      verification(){
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let params = JSON.parse(JSON.stringify(this.dataForm))
            params.body = ""
            params.bodyData = params.bodyData?JSON.parse(params.bodyData):''
            params.heardData = params.heardData?JSON.parse(params.heardData):''
            this.conmitFormData = JSON.parse(JSON.stringify(params))

            request({
              url:`/ht-datadevelop/token/manage/getApiTokenCheck`,
              method: 'post',
              data: this.conmitFormData
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.veriicationStr = data.token
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      onJsonChange (value) {
        // 实时保存
        this.onJsonSave(value)
      },
      onJsonSave (value) {
        this.resultInfo = value
        this.hasJsonFlag = true
      },
      onError(value) {
        this.hasJsonFlag = false
      },
      // 检查json
      checkJson(){
        this.dataForm[this.jsonType] = JSON.stringify(this.resultInfo)
        this.editPostJsonFlag = false
        return true
      },
      editJson (v,jsonObj) {
        if(jsonObj){
          this.resultInfo = JSON.parse(jsonObj) //json编辑器数据
        }else{
          this.resultInfo = {}
        }
        this.jsonType = v
        this.editPostJsonFlag = true
      },
      selecttag (tag, i) {
        this.methodsList.forEach((item,index)=> {
          item.type = ""
        })
        this.methodsList[i].type = "warning"
        this.dataForm['method'] = tag.name
      },
      editData(v){
        if(v.add){
          //这里是新增
          this.isYzFlag = false
        }else{
          this.isYzFlag = true //修改显示字段
        }
        this.visible = true
        this.dataForm = JSON.parse(JSON.stringify(v)) //复制编辑对象数据

        this.dataForm.jsonBody = v.jsonBody?JSON.stringify(v.jsonBody):null //用来显示的字符串数据
        this.dataForm.jsonHeard =v.jsonHeard?JSON.stringify(v.jsonHeard):null //用来显示的字符串数据
        this.dataForm.jsonKeyReplaceValue =v.jsonKeyReplaceValue?JSON.stringify(v.jsonKeyReplaceValue):null

        this.methodsList.forEach((item,index)=> {
          if(item.name==v.method){
            item.type = "warning"
          }
        })
      },
      init (row) {
        // request({
        //   url: /ht-datadevelop/sys/common/getContentTypeList'),
        //   method: 'get',
        //   params:{}
        // }).then(({data}) => {
        //    this.visible = true
        //    this.options = data.list
        // })
        // request({
        //   url:/ht-datadevelop/token/manage/listToken'),
        //   method: 'get',
        //   params:{}
        // }).then(({data}) => {
        //   this.pageIdList  = data.page
        // })
        // request({
        //   url: /ht-datadevelop/sys/common/getRequestMethodList'),
        //   method: 'get',
        //   params:{token:Vue.cookie.get('token')}
        // }).then(({data}) => {
        //   this.methodsList  = []
        //   data.list.forEach((item,index)=>{
        //     this.methodsList.push({
        //       name:item,
        //       type:''
        //     })
        //   })
          if(row){
            this.editData(row)
          }
        // })
      },
      // 表单提交
      dataFormSubmit () {
        if(!this.isYzFlag){
          return 
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            let param = JSON.parse(JSON.stringify(this.dataForm))
            param.jsonBody = param.jsonBody==''?null:JSON.parse(param.jsonBody)
            request({
              url:`/ht-datadevelop/table/jsondata/jsonDataSaveOrUpdate`,
              method: 'post',
              data: param
            }).then((res) => {
              if (res.code === 200) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 500,
                  onClose: () => {
                    this.closeDialog()
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(res.msg)
              }
            })
          }
        })
      }
    }
  }
</script>


<style lang="scss" scoped>
  .oneCls{
    >div{
      position: relative;
      >button{
        position: absolute;
        right: 0;
      }
    }
  }
>>>.el-form-item__content{
  position: relative;
}
>>>.el-textarea__inner{
  min-height:220px !important;
  max-height:220px !important;
}
>>>.info{
    position: absolute;
    left: 0;
    top:26px;
    font-size: 10px;
    width:100%;
    color: #ff9100;
  }
  >>>.el-select{
    display: block !important;
  }
  .el-form{
    // display: flex;
    // flex-direction: row;
    // flex-wrap: wrap;
  }
  .el-form-item{
    // width: 50%;
  }
  .el-form-item:nth-child(1){
    .el-input{
      width:75%;
    }
  }
 ul{
  margin-left: 0 !important;
  padding-left: 0 !important;
  .lis{
    margin-bottom: 6px;
    list-style: none;
    display: flex;
    span:nth-child(1){
      width: 45%;
    }
    span:nth-child(2){
      width: 45%;
    }
    span:nth-child(3){
      width: 10%;
      text-align: center;
      padding-top: 6px;
      cursor: pointer;
      color: red;
    }
    span{
      display: block;
      >>>.el-input{
        display: inline-block;
        width:80%;
      }
    }
  }
 }
</style>
